

#include <colorPickButton.h>
#include <renderer.h>
#include <input.h>
#include <drawingWidget.h>

ColorPickButton::ColorPickButton(){

paletteSize.x=256;
paletteSize.y=128;
textureID="icon_colorPad";
}
ColorPickButton::~ColorPickButton(){}


void ColorPickButton::setup(){
Button::setup();

}

void ColorPickButton::update(double deltaTime){

if (input->focusButton==this)
  pickColor();
}

void ColorPickButton::mouseOver(){

Button::mouseOver();
}

void ColorPickButton::mouseDrag(){

}

void ColorPickButton::clickedLeft(){

if (DrawingWidget::brush)
  DrawingWidget::brush->color=color;
}

void ColorPickButton::clickedRight(){

input->focusButton=this;
}

void ColorPickButton::focusClick(){

Button::focusClick();
}

void ColorPickButton::pickColor(){

float hue= input->mouseX-location.x;
float bright= location.y - input->mouseY;

float greyArea=(paletteSize.x/128)*16;
float colorArea=paletteSize.x-greyArea;
float colorStep=colorArea/3;

color=Vector4f(0,0,0,1);

//R
if (hue<colorStep)
  color.r=1-(hue/colorStep);
if (hue>2*colorStep)
  color.r=(hue-2*colorStep)/(colorStep);
if (color.r<0) color.r=0;

//G
if (hue<colorStep)
  color.g=hue/colorStep;
if (hue>=colorStep)
  color.g=1-(hue-colorStep)/colorStep;
if (color.g<0) color.g=0;

//B
if (hue<2*colorStep)
  color.b=(hue-colorStep)/colorStep;
if (hue>=2*colorStep)
  color.b=1-(hue-2*colorStep)/colorStep;
if (color.b<0) color.b=0;

bright=bright/paletteSize.y;        //Values from 0 to 1
bright=(bright-0.5)*(-2);            //gives values from -1 to 1

Vector4f brightness=Vector4f(1,1,1,1)*bright;
color+=brightness;
color.a=1;
if (color.r>1) color.r=1;
if (color.g>1) color.g=1;
if (color.b>1) color.b=1;

clickedLeft();
}

void ColorPickButton::drawPlane(){

Button::drawPlane();

glColor3f(1,1,1);
glBindTexture(GL_TEXTURE_2D,renderer->textureList["icon_palette"]->texture);
if (input->focusButton==this)
  {
   glTranslatef(0.0,-paletteSize.y,0.0);
   glBegin(GL_QUADS);
		glTexCoord2f(0.0,0.0);
		glVertex3f(0,0,0.0);
        glTexCoord2f(1.0,0.0);
        glVertex3f(paletteSize.x,0,0.0);
        glTexCoord2f(1.0,1.0);
		glVertex3f(paletteSize.x,paletteSize.y,0.0);
        glTexCoord2f(0.0,1.0);
		glVertex3f(0,paletteSize.y,0.0);
	glEnd();
  }
}

void ColorPickButton::deselect(int depth){

Button::deselect(depth);
}

void ColorPickButton::create(){renderer->addButton(this);}
